package com.mhuang.module.common.controller;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.LoggerFactory;

import com.mhuang.common.utils.network.NetWorkUtils;


/**
 * 基础CONTROLLER
 * @author mHuang
 *
 */
public class BaseController {

	public static final String CODE = "code";
	public static final String OPENID = "openId";
	public static final String USER = "user";
	public static final String HTML = "html";
	public static final String STATE = "state";
	public static final String STATUS = "status";
	public static final String USERTYPE = "userType";
	public static final String MESSAGE =  "message";
	public static final String USERID = "userid";
 	public static final String TOKEN = "token"; 
 	public static final String TYPE = "type";
 	/**系统*/
 	public static final String SYSTEMTYPE = "systemType";
 	public static final String RECOMMEND = "recommend";
	public static final String PAGE ="page";
	public static final String ANSWER = "answer";
 	public static boolean isWechat(HttpServletRequest request){
		boolean validation = false;
		if(StringUtils.isNotEmpty(request.getHeader("user-agent"))){
		    String ua = request.getHeader("user-agent").toLowerCase();
	        if (ua.indexOf("micromessenger") > 0) {// 是微信浏览器
	            validation = true;
	        }
		}
		return validation;
	}

	public static String getOpenId(){
		return null;
	}
	
	public static String oauth2(String url,HttpServletRequest request){
		try{
			return NetWorkUtils.sync(url.replace(CODE.toUpperCase(),request(request,CODE)));
		}catch(Exception e){
			LoggerFactory.getLogger(BaseController.class).error("微信网页授权异常",e);
			return null;
		}
	}
	
	public static Map<String, String> allRequestMap(HttpServletRequest request){
		return describe(request);
	}
	
	public static String allRequestString(HttpServletRequest request){
	    return describeStr(request);
	}
	
	public static String request(HttpServletRequest request,String key){
		return request.getParameter(key);
	}
	
	public static HttpSession session(HttpServletRequest request){
		return request.getSession();
	}
	public static Object session(HttpServletRequest request,String id){
		return session(request).getAttribute(id);
	}
	public static Object attribute(HttpServletRequest request,String key){
		return request.getAttribute(key);
	}
	
	public static String requestUrl(HttpServletRequest request){
		String queryString = request.getQueryString();
		if(StringUtils.isNotBlank(queryString)){
			return request.getRequestURL().append("?").append(request.getQueryString()).toString();
		}
		return request.getRequestURL().toString();
	}
	
	public static Map<String, String> describe(HttpServletRequest request)
	{
		Map<String,String> reMap=new HashMap<String,String>();
		//获取所有客户端提交参数的Map
		Map<String, String[]> pars=request.getParameterMap();
		//获取Map中所有实体的集合
		Set<Entry<String, String[]>> entitySet=pars.entrySet();
		//遍历集合
		for(Map.Entry<String, String[]> entity:entitySet){
		    if(entity.getValue().length==1){
				reMap.put(entity.getKey(), (entity.getValue())[0]);	
			}
		}
		return reMap;
	}
	
	public static String describeStr(HttpServletRequest request)
    {
	    String str = "";
        //获取所有客户端提交参数的Map
        Map<String, String[]> pars=request.getParameterMap();
        Set<Entry<String, String[]>> entitySet=pars.entrySet();
        for(Map.Entry<String, String[]> entity:entitySet){
            str = entity.getKey();
        }
        return str;
    }
	
	public static Map<String, String> parseXml(String request){
		Map<String, String> map = new HashMap<String, String>();  
		try{
		    // 读取输入流  
		    Document document = DocumentHelper.parseText(request);  
		    parse(map, document);  
		}catch(Exception e){
			e.printStackTrace();
		}
	    return map;
	}
	
	public static Map<String, String> parseXml(HttpServletRequest request){ 
		// 将解析结果存储在HashMap中  
		Map<String, String> map = new HashMap<String, String>();  
		try{
		    // 从request中取得输入流  
		    InputStream inputStream = request.getInputStream();  
		    // 读取输入流  
		    SAXReader reader = new SAXReader();  
		    Document document = reader.read(inputStream);  
		    parse(map,document);  
		    // 释放资源  
		    inputStream.close();  
		    inputStream = null;
		}catch(Exception e){
			e.printStackTrace();
		}
	    return map;
	}
	
	private static void parse(Map<String, String> map,Document document){
		 // 得到xml根元素  
	    Element root = document.getRootElement();  
	    
	    // 得到根元素的所有子节点  
	    @SuppressWarnings("unchecked")
		List<Element> elementList = root.elements();  
	   
	    // 遍历所有子节点  
	    for (Element e : elementList)  
	        map.put(e.getName(), e.getText());  
	} 
}
